/**
 * 用户授权
 */
let config = require('../config');
let ErrorUtils = require('../utils/error/ErrorUtils');
const {errorLogger, infoLogger, con} = require('../config').logger;
let redis = require('../redis');
let lodash=require('lodash');
const userTtl = 3600 * 2;
module.exports = () => {
    return async function (ctx, next) {
        let headers = ctx.header;
        infoLogger.info(">>>>小程序鉴权中间件处理开始",headers);
        if (!headers) {
            ctx.status = 401;
            infoLogger.error('401 url - ' + ctx.url + 'header不存在');
            ErrorUtils.throwApiError(ErrorUtils.AUTH_FAIL);
        }
        if (!headers.hasOwnProperty(config.auth.access_key)) {
            ctx.status = 401;
            ErrorUtils.throwApiError(ErrorUtils.AUTH_FAIL);
            infoLogger.info('401 url - ', ctx.url);
        }
        let aceessToken = headers[config.auth.access_key];
        let userInfo = await redis.get(`${config.auth.adminLoginPrefix}${aceessToken}`);
        if (!userInfo || JSON.stringify(userInfo) == '{}') {
            infoLogger.info('401 userinfo- ', userInfo);
            infoLogger.info('401 url - ', ctx.url);
            ctx.status = 401;
            ErrorUtils.throwApiError(ErrorUtils.AUTH_FAIL);
        } else {
            userInfo = JSON.parse(userInfo);
            userInfo = lodash.omit(userInfo, ['password']);
            ctx.currentUser=userInfo;
            await redis.expire(`${config.auth.adminLoginPrefix}${aceessToken}`, config.auth.adminTtl);
            await next();
            infoLogger.info(">>>>小程序鉴权中间件处理开始");
        }
    }
};

